<template>
  <!-- 物流资金计划 -->
  <PageTab>
    <template #search>
      <VForm
        ref="formRef"
        :fieldList="fieldList"
        :options="formOption"
        @submit="handleSearch"
        @reset="handleSearch"
        :originOption="optionsDataAll"
      />
    </template>
    <template #tab>
      <el-tabs
        v-model="activeName"
        class="tabs"
        @tab-change="handleStatusChange"
      >
        <el-tab-pane
          :label="item.label"
          :name="item.value"
          v-for="item in tabs"
          :key="item.value"
        ></el-tab-pane>
      </el-tabs>
      <ActionBar class="mt-[-16px]" :actions="actions">
        <template #left>
          <el-select
            v-if="
              activeName === 'HISTORY_4_WEEK' ||
              activeName === 'HISTORY_WEEK' ||
              activeName === 'HISTORY_MONTH'
            "
            v-model="pay_due_date"
            placeholder="请选择历史周期"
            clearable
            @change="handleDueDate"
            style="width: 240px; margin-right: 8px"
          >
            <el-option
              v-for="item in pay_due_date_list"
              :key="item.snapshot_cycle_md5"
              :label="item.show_cycle"
              :value="item.snapshot_cycle_md5"
            />
          </el-select>
        </template>
      </ActionBar>
    </template>
    <Table
      ref="tableRef"
      :params="params"
      :type="activeName"
      :dueDate="dueDate"
      @edit="handleEdit"
      @submit="handleSubmit"
      @audit="handleAudit"
      @delete="handleDelete"
    />
    <add
      v-model="addVisible"
      @refresh="handleRefresh"
      :id="id"
      :optionsData="optionsDataAll"
      @close="id = null"
    />
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
    <ConfirmInput
      title="审核"
      class="w-[500px]"
      confirmButtonText="确认"
      v-model="approvalVisible"
      :loading="loading"
      :field-options="approvalOptions"
      :rules="approvalRules"
      @submit="handleApprovalReq"
    />
    <ImportDialog ref="importDialogRef" @refresh="handleRefresh" />
  </PageTab>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import PageTab from "@/components/PageTab/index.vue";
import VForm from "@/components/Form/index.vue";
import ActionBar from "@/components/ActionBar/index.vue";
import ConfirmInput from "@/components/ConfirmInput/index.vue";
import Table from "./components/Table/index.vue";
import { financeManageAuthList } from "@/Auth/finance-manage.js";
import DerivedCenter from "@/components/DerivedCenter/index.vue";
import { config_name } from "@/config/export.js";
import add from "./components/add/index.vue";
import { useEnumSelect } from "@/hooks";
import { useFetchSelect } from "@/hooks";
import { snapshotCycle, opSure, opSubmit, lfpDelete } from "./api/index.js";
import { getTableSelectRowOld } from "@/hooks/tool.js";
import ImportDialog from "@/components/importDialog/index.vue";
import { formatTime } from "@/utils/time.js";
const { proxy } = getCurrentInstance();
const activeName = ref("NEXT_WEEK");
const tableRef = ref();
const params = ref();

const pay_due_date_list = ref([]);
const pay_due_date = ref(null);
const getSnapshotCycle = async (type) => {
  try {
    let { data } = await snapshotCycle({ snapshot_type: type });
    pay_due_date_list.value = data || [];
    pay_due_date.value = data.length
      ? data[0]?.snapshot_cycle_md5 || null
      : null;
  } catch (error) {
    pay_due_date_list.value = [];
    pay_due_date.value = null;
  }
};
// getSnapshotCycle("NEXT_WEEK");
const handleStatusChange = async (e) => {
  params.value = {
    ...params.value,
    snapshot_cycle_md5: null,
    now_date: formatTime(null, "YYYY-MM-DD HH:mm:ss"),
  };
  if (e === "HISTORY_4_WEEK" || e === "HISTORY_WEEK" || e === "HISTORY_MONTH") {
    await getSnapshotCycle(e);
    params.value = { ...params.value, snapshot_cycle_md5: pay_due_date.value };
  }
  nextTick(() => {
    handleRefresh();
  });
};
// const dueDate = ref([])
const dueDate = computed(() => {
  if (pay_due_date.value) {
    let item = pay_due_date_list.value?.find(
      (item) => item.snapshot_cycle_md5 === pay_due_date.value
    );
    return item?.snapshot_cycle || [];
  }
  return [];
});
const handleDueDate = (e) => {
  params.value = {
    ...params.value,
    snapshot_cycle_md5: pay_due_date.value || null,
  };
  nextTick(() => {
    handleRefresh();
  });
};

const handleSearch = (values) => {
  const { time } = values || {};
  params.value = {
    ...values,
    [time?.key]: time?.value,
    time: undefined,
    now_date: formatTime(null, "YYYY-MM-DD HH:mm:ss"),
  };
  handleRefresh();
};
const handleRefresh = () => {
  nextTick(() => {
    tableRef.value?.tableRef.commitProxy("reload");
  });
};
//导出
const DerivedCenterRef = ref();
const handleExport = async () => {
  let condition = getTableSelectRowOld(tableRef.value?.tableRef, params.value);
  DerivedCenterRef.value.open({
    tag_name: config_name["finance_manage"]["lfp"],
    condition,
  });
};

const formOption = {
  inline: true,
  option: true,
  showResetButton: true,
};
const { options: optionsData } = useEnumSelect({
  params: [
    "finance_lfp_payment_type",
    "finance_charge_status",
    "finance_lpo_pay_main_company",
    "finance_lfp_snapshot_type",
  ],
});
const { options: optionsData1 } = useFetchSelect({
  params: ["map.logistics"],
});
const optionsDataAll = computed(() =>
  Object.assign({}, optionsData.value, optionsData1.value)
);

const tabs = computed(() => optionsDataAll.value["finance_lfp_snapshot_type"]);
const id = ref(null);
const addVisible = ref(false);
const handleAdd = () => {
  addVisible.value = true;
};

const handleEdit = (item) => {
  addVisible.value = true;
  id.value = item?.id;
};

const publicStyle = { style: { width: "300px" } };
const fieldList = [
  {
    field: "logistics_id",
    type: "select",
    originField: "map.logistics",
    options: {
      placeholder: "物流商名称",
      labelKey: "logistics_name",
      valueKey: "logistics_id",
    },
    collapseTags: true,
    multiple: true,
  },
  {
    field: "settle_type",
    type: "select",
    originField: "finance_lfp_settle_type",
    options: {
      placeholder: "结算类型",
    },
    style: { width: "100px" },
  },
  {
    field: "pay_main_company_id",
    type: "select",
    originField: "finance_lpo_pay_main_company",
    options: {
      placeholder: "付款主体",
    },
  },
  {
    field: "time",
    type: "dateTimeRange",
    style: { width: "360px" },
    selectStyle: { width: "120px" },
    select: [{ label: "贷款所属期", value: "pay_due_date" }],
    itemProps: {
      startPlaceholder: "最早时间",
      endPlaceholder: "最晚时间",
    },
  },
];
const getSelectRows = () => {
  const rows = tableRef.value?.tableRef.getCheckboxRecords();
  if (!rows?.length) {
    ElMessage({
      showClose: true,
      message: "请至少选择一条数据！",
      type: "warning",
    });
    return [];
  }
  return rows;
};
const handleBatchSubmit = () => {
  const rows = getSelectRows();
  if (!rows.length) return;
  const id = rows.map((n) => n.id);
  handleSubmitReq(id);
};
const handleSubmit = (id) => {
  handleSubmitReq(id);
};
const handleSubmitReq = (id) => {
  proxy?.confirm({
    title: "提示",
    content: <p>确认提交 {id?.length || 1} 条数据？</p>,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message } = await opSubmit({
            id,
          });
          if (code !== 200) {
            ElMessage.warning(message);
            return;
          }
          ElMessage.success("提交成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          handleRefresh();
        }
      } else {
        done();
      }
    },
  });
};
const handleBatchDelete = () => {
  const rows = getSelectRows();
  if (!rows.length) return;
  const id = rows.map((n) => n.id);
  handleDeleteReq(id);
};
const handleDelete = (id) => {
  handleDeleteReq(id);
};
const handleDeleteReq = (id) => {
  proxy?.confirm({
    title: "提示",
    content: <p>确认删除 {id?.length || 1} 条数据？</p>,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message } = await lfpDelete({
            id,
          });
          if (code !== 200) {
            ElMessage.warning(message);
            return;
          }
          ElMessage.success("删除成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          handleRefresh();
        }
      } else {
        done();
      }
    },
  });
};
const approvalOptions = [
  {
    label: "审核状态",
    field: "audit",
    type: "radio",
    style: { width: "100%" },
    options: {
      data: [
        { label: "通过", value: "pass" },
        { label: "驳回", value: "rejected" },
      ],
    },
    itemProps: {
      popperAppendToBody: true,
      teleported: true,
    },
  },
  {
    label: "驳回原因",
    field: "remark",
    type: "textarea",
    style: { marginTop: "10px" },
    autosize: { minRows: 4, maxRows: 8 },
    show: ({ model }) => model.audit === "rejected",
  },
];
const approvalRules = {
  audit: [{ required: true, message: "请选择审核状态", trigger: "blur" }],
};
const approvalVisible = ref(false);
const loading = ref(false);
const auditData = ref(null);
const handleAudit = (id) => {
  approvalVisible.value = true;
  auditData.value = id;
};
const handleBatchAudit = () => {
  const rows = getSelectRows();
  if (!rows.length) return;
  const id = rows.map((n) => n.id);
  approvalVisible.value = true;
  auditData.value = id;
};
const handleApprovalReq = async (formValues) => {
  const obj = {
    id: auditData.value,
    ...formValues,
  };
  try {
    loading.value = true;
    const { code, message } = await opSure(obj);
    if (code !== 200) {
      ElMessage.warning(message);
      return;
    }
    ElMessage.success("操作成功");
    auditData.value = null;
    approvalVisible.value = false;
    handleRefresh();
  } catch (e) {
  } finally {
    loading.value = false;
  }
};
const importDialogRef = ref();
const handleImport = () => {
  importDialogRef.value?.open({
    type: "finance.logisticsFundPlan",
    urlType: "/finance/lfp/import",
  });
};
const actions = [
  {
    label: "新增",
    type: "primary",
    fn: handleAdd,
    show: () => activeName.value === "NEXT_WEEK",
    permission: [financeManageAuthList.fund_plan.add],
  },
  {
    label: "批量提交",
    type: "primary",
    fn: handleBatchSubmit,
    show: () => activeName.value === "NEXT_WEEK",
    permission: [financeManageAuthList.fund_plan.submit],
  },
  {
    label: "批量财务确认",
    type: "primary",
    fn: handleBatchAudit,
    show: () => activeName.value === "NEXT_WEEK",
    permission: [financeManageAuthList.fund_plan.audit],
  },
  {
    label: "批量删除",
    fn: handleBatchDelete,
    show: () => activeName.value === "NEXT_WEEK",
    permission: [financeManageAuthList.fund_plan.delete],
  },
  {
    label: "导入",
    right: true,
    fn: handleImport,
    show: () => activeName.value === "NEXT_WEEK",
    permission: [financeManageAuthList.fund_plan.import],
  },
  {
    label: "导出",
    right: true,
    fn: handleExport,
    permission: [financeManageAuthList.fund_plan.export],
  },
];
</script>

<style lang="scss" scoped>
@import "@/components/PageTab/tab.scss";
</style>
